package com.skywork.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.skywork.controller.response.TokenResponse;
import com.skywork.domain.AccessToken;
import com.skywork.domain.Channel;
import com.skywork.service.AccessTokenService;
import com.skywork.utils.ChannelKit;
import com.skywork.utils.SignUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@RestController
@Api(value = "Token Service")
@RequestMapping(value = "/token")
public class TokenController {

	@Autowired
	private AccessTokenService accessTokenService;

	@Autowired
	private com.skywork.service.ChannelService channelService;

	@ApiOperation(value = "获取access_token", notes = "获取access_token")
	@RequestMapping(value = "/{channelCode}", method = RequestMethod.GET)
	public TokenResponse getAccessTokenByChannelId(@PathVariable(value = "channelCode") String channelCode, @RequestParam(value = "timestamp") Long timestamp, @RequestParam(value = "sign") String sign) {
		TokenResponse tokenResponse = new TokenResponse();
		Channel channel = channelService.findByCode(channelCode);
		if (channel != null && SignUtil.checkSignature(null, channel, timestamp, sign)) {
			ChannelKit.setThreadLocalChannel(channel);
			AccessToken accessToken = accessTokenService.getAccessTokenByChannelId(channel);
			tokenResponse.setToken(accessToken.getToken());
			tokenResponse.setExpiresIn(accessToken.getExpiresIn());
		} else {
			tokenResponse.setCode("404");
			tokenResponse.setMessage("Get token Error,Place check Param!");
		}
		return tokenResponse;
	}

}
